<template>
<div class="app-container">
  <div class="staff">
    <div class="form-top">
      <i class="el-icon-menu"></i>
      <span class="form-title">
          基本信息
      </span>
    </div>
    <el-form  :model="formLabel" label-width="150px" :inline="true" :rules="rules" ref="formLabel">
      <div class="left100">
      <el-row class='wd950'>
        <el-col :span="12">
          <el-form-item label="保险公司：" class="is-required" prop="insuranceId">
            <!--<el-select v-model="formLabel.insuranceId" placeholder="请选择" size="mini" class="wd230">
              <el-option v-for="item in companies" :key="item.id" :value="item.id" :label="item.insuranceName">
              </el-option>
            </el-select>-->
            <el-select  class="wd230" size="mini" v-model="formLabel.insuranceId" placeholder="请选择保险公司" >
							<el-option-group v-for="group in companies" :key="group.letter" :label="group.letter" @change="comchange(formLabel.insuranceId)">
								<el-option v-for="item in group.insurances" :key="item.id" :label="item.insuranceName" :value="item.id">
								</el-option>
							</el-option-group>
						</el-select>
          </el-form-item>
          <el-form-item label="密码：" class="is-required" prop="staffPassword">
            <el-input v-model="formLabel.staffPassword" placeholder="请填写密码" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="机构代码：">
            <el-input v-model="formLabel.insuranceCode" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="VPN地址：">
            <el-input v-model="formLabel.vpnAddress" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="VPN登录密码：">
            <el-input v-model="formLabel.vpnPassword" placeholder="" size="small"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="IP地址：">
            <el-input v-model="formLabel.ip" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="出单平台锁定登录：">
            <el-select v-model="formLabel.isSystemLocked" placeholder="请选择" size="mini" class="wd230">
              <el-option v-for="item in status" :key="item.value" :value="item.isSystemLocked" :label="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号：">
            <el-input v-model="formLabel.phoneNumber" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工号："  class="is-required" prop="staffAccount">
            <el-input v-model="formLabel.staffAccount" placeholder="请填写工号" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="工号描述："  class="is-required" prop="describe">
            <el-input v-model="formLabel.describe" placeholder="请填写工号描述" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="状态：">
            <el-select v-model="formLabel.isActive" placeholder="请选择" size="mini" class="wd230">
              <el-option v-for="item in status2" :key="item.value2" :value="item.isActive" :label="item.value2">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="VPN登录名：">
            <el-input v-model="formLabel.vpnAccount" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="Mac地址：">
            <el-input v-model="formLabel.mac" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="机器码：">
            <el-input v-model="formLabel.machineCode" placeholder="" size="mini"  class="wd230"></el-input>
          </el-form-item>
          <el-form-item label="使用录单：">
            <el-select v-model="formLabel.isRecord" placeholder="请选择" size="mini" class="wd230">
              <el-option v-for="item in status3" :value-key="item.value3" :value="item.isRecord" :label="item.value3">
              </el-option>
            </el-select>
          </el-form-item>
          
          <!--<el-form-item label="所属机构：" v-show="taishan">
            <el-select v-model="formLabel.isRecord" placeholder="请选择" size="mini" class="wd230">
              <el-option v-for="item in status3" :value-key="item.value3" :value="item.isRecord" :label="item.value3">
              </el-option>
            </el-select>
          </el-form-item>-->
          
        </el-col>
        <el-col :span='24'>
        	
          <el-form-item label="工号所属区域：" class="offsetR is-required floatLeft regionId" prop="regionId">
            <el-select v-model="value1" placeholder="请选择省" @change='linkage2' size="mini">
              <el-option v-for="item in aoptions" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
            <div class="hiddenInput">
              <el-input type="hidden"  v-model="formLabel.regionId"></el-input>
            </div>
           
          </el-form-item>
          
          <el-form-item class="offsetR is-required floatLeft" prop="value2">
            <el-select v-if="id!=0" v-model="formLabel.value2" placeholder="请选择市"  @change='linkage3' size="mini">
              <el-option v-for="item in boptions" :key="item.key" :label="item.conentname" :value="item.key">
               <span>{{ item.value }}({{ item.plateCode}})</span>
              </el-option>
            </el-select>
             <el-select v-else v-model="formLabel.value2" placeholder="请选择市"  @change='linkage3' size="mini">
              <el-option v-for="item in boptions" :key="item.key" :label="item.conentname" :value="item">
               <span>{{ item.value }}({{ item.plateCode}})</span>
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item class="offsetR is-required floatLeft">
            <el-select v-model="value3" placeholder="请选择区"  @change='linkage4' size="mini">
              <el-option v-for="item in coptions" :key="item.key" :label="item.value" :value="item.key">
              </el-option>
            </el-select>
          </el-form-item>
          
          
        </el-col>
        <el-col :span='24'>
          <el-form-item label="关联组织：" class="offsetR toBlock org" prop="orgs">
            <div style="width:700px;margin-bottom:10px;">
              <!-- <span class="setColor1" v-if="treename.length != 0 && orgs.length==0">已选中{{treename.length}}个组织</span> -->
              <span class="setColor1" v-if="treeSelect.length != 0">已选中{{treeSelect.length}}个组织</span>
              <!-- <span class="setColor" @click="openTree = true" v-for="org in orgs" v-if="orgs">{{org.fullName}}</span>
              <span class="setColor" @click="openTree = true" v-for="tree in treename" v-if="treename && orgs.length==0">{{tree}}</span> -->
            </div>
            <el-button size="mini" @click="openTree = true" class="toBlock"><i class="iconfont icon-organization"></i>&nbsp;{{org}}</el-button>
            <div class="hiddenInput">
              <el-input type="hidden"  v-model="formLabel.orgs"></el-input>
            </div>
          </el-form-item>
          <el-dialog title="选择组织" :visible.sync="openTree" @close="backs" :close-on-click-modal='false' width='500px'>
              <div class="fix">
                <el-tree
                  :data="organizationUnitTree"
                  show-checkbox
                  node-key="id"
                  :default-expand-all='true'
                  :default-checked-keys="treeSelect"
                  :props="defaultProps"
                  ref="tree"
                 >
                </el-tree>
              </div>
              <div slot="footer" class="dialog-footer">
                <el-button @click="backs">取 消</el-button>
                <el-button type="primary"  @click="getCheckedKeys()">确 定</el-button>
              </div>
            </el-dialog>
          <el-form-item label="备注信息：" class="offsetR toBlock">
            <el-input
              type="textarea"
              :autosize="{minRows:3}"
              placeholder="请输入内容"
              v-model="formLabel.remark" style="width:688px">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span='24'>
          <el-row class="center">
            
            <el-button type="info" size="small" @click="resetForm('formLabel')">取消</el-button>
            <el-button type="primary" size="small" @click="submitForm('formLabel')">保存</el-button>
          </el-row>
        </el-col>
      </el-row>
      </div>
    </el-form>
  </div>
</div>


</template>
<script>
export default {
  data() {
    return {
    	taishan:false,
      value1:'',
      organizationUnitTree: [],
      openTree: false,
      //公司数据
      companies:[],
      aoptions:[],
      coptions:[],
      value3:'',
      options:[],
      value2:'',
      boptions:[],
     		status: [{
	        isSystemLocked: true,
	        value: '正常'
	      }, {
	        isSystemLocked: false,
	        value: '禁用'
	      }
	      ],
	      status2: [{
	        isActive: true,
	        value2: '正常'
	      }, {
	        isActive: false,
	        value2: '禁用'
	      }
	      ],
	      status3: [{
	        isRecord: true,
	        value3: '正常'
	      }, {
	        isRecord: false,
	        value3: '禁用'
	      }
	      ],
      // 省数据
      provices: [],
      // 市数据
      cities: [],
      // 区数据
      areas: [],
      org: '选择组织',
      orgs:[],
      regionIds:[],
      formLabel: { 
      	insuranceId:'',
        orgs:[],        
	      isSystemLocked: true,
	      isActive: true,
	      isRecord: true,
	      value2:''
      },
      defaultProps: {
        children: 'organizationUnits',
        label: 'displayName'
      },
      //级联
      options2:[],
      props: {
          value: 'key',
          label:'value',
          children: 'children'
      },
      rules: {
        insuranceId: [{ required: true, message: '请输入保险公司', trigger: 'change' }],
        staffPassword: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        staffAccount: [{ required: true, message: '请输入工号', trigger: 'blur' }],
        describe: [{ required: true, message: '请输入工号描述', trigger: 'blur' }],
        regionId: [{ required: true, message: '请选择完整的区域', trigger: 'change' }],
        value2: [{ required: true, message: '请选择完整的区域', trigger: 'change' }],
        orgs: [{ required: true, message: '请至少选择一个组织', trigger: 'change' }]
      },
      from: false, // 来自哪里，false为新建，true为更新
      treename:[],
      treeArr:[],
      idArr:[],
      id:'',
      treeSelect:[]
    }
  },
  mounted() {
   
    this.id = this.$route.params.id
      console.log('------------')
     console.log(111111)
     this.getCompanies()
    console.log(this.id)
    if (this.id!= '0') {
      this.getInfo()
      this.from = true
      console.log("bianji")
    }else{
    	this.linkage()
    	
    	this.linkage2()
    	
    	//this.linkage3()
    	
    }
  
   // this.getProvices()
    this.getTree()
  
    
  },
  watch:{

  },
  methods: {
  	 // 公司
    getCompanies() {
    	 console.log(22222)
      let that = this
      let params = {}
      this.post(params, 'services/app/common/GetGroupInsurances').then(rs => {
        console.log(rs)
        if (rs.success) {
          that.companies = rs.result.items
        }
      })
    },
    // 级联
    handleItemChange(val){
      console.warn('级联'+val);
      const that = this;
      // console.warn(val.length);
     if (val.length == 1) {
        this.getCities(val);
      } else if (val.length == 2) {
        this.getAreas(val);
      }
    },
    // getAreaId(val){
    //   console.warn(val);
    //   this.formLabel.regionId = val[val.length-1];
    //   // console.warn(this.formLabel.regionId);
    // },
    //得到权限集合
    treearray(data) {
      // console.log(data)
      var treeArr = [];
      var treeNames = [];
      data.map(function (item) {
        if (item.isCheck) {
          treeArr.push(item.id)
          treeNames.push(item.fullName)
        }
        if (item.organizationUnits) { //遍历2级
          item.organizationUnits .map(function (elem) {
            if (elem.isCheck) {
              treeArr.push(elem.id)
              treeNames.push(elem.fullName)
            }
            if (elem.organizationUnits) { //遍历3级
              elem.organizationUnits .map(function (obj) {
                if (obj.isCheck ) {
                  treeArr.push(obj.id)
                  treeNames.push(obj.fullName)
                }

                if (obj.organizationUnits!== null &&obj.organizationUnits) { //遍历4级
                  obj.organizationUnits .map(function (last) {
                    if (last.isCheck ) {
                      treeArr.push(last.id)
                      treeNames.push(last.fullName)
                    }
                    //遍历3级
                  })
                }
              })
            }
          })
        }
      })
      return {treeArr,treeNames};
    },
    // 详细
    getInfo() {
      const that = this
      const params = {
        id: this.id
      }
      this.post(params, 'services/app/staff/GetStaffDetail').then(rs => {
           console.log('-------------')
           console.log(rs)
        if (rs.success) {
          that.from = true
          this.formLabel = rs.result.staff;
          console.log('77777...')
          console.log(rs)
          if(rs.result.organizationUnitIds){
            this.formLabel.orgs = rs.result.organizationUnitIds;
            this.treeSelect = rs.result.organizationUnitIds
          }
          if(rs.result.staff.regionIds){
            let regionIds = rs.result.staff.regionIds;
            console.log("shuzushuju")
            console.log(regionIds)
            	this.idArr[0] = regionIds.provinceId
            	this.idArr[1] = regionIds.cityId
            	this.idArr[2] = regionIds.areaId
            	console.log("获取数据-------------")
         			this.linkage()
         				this.value1=regionIds.provinceId;
					    this.linkage2(regionIds.provinceId)
					    this.formLabel.value2=regionIds.cityId;
					    this.linkage3(regionIds.cityId)
							console.log("vue2复制")
							this.value3 = regionIds.areaId	
							
							
							
							
//							  new Promise(function(resolve, reject) {
//          			that.linkage()
//          			console.log(111)
//		              resolve("ddd");
//		            })
//		              .then(function(data) {
//		                that.linkage2(regionIds.provinceId)
//		              })
//		              .then(function(data) {
//		               	 //that.linkage3(regionIds.provinceId)
//		              })
//		              .then(function(data) {
//		               	 	that.value1=regionIds.provinceId;  
//											that.value2=regionIds.cityId;
//											
//											that.value3 = regionIds.areaId	
//		                	console.log("vue2复制")
//		              });
							
							
          }

          // 树 弃用2018年7月25日09:35
          //that.treeArr = that.treearray(rs.result.organizationUnitTree).treeArr;
         // that.treename = that.treearray(rs.result.organizationUnitTree).treeNames
        }
      })
    },
    // 树
    getTree() {
      const params = []
      this.post(params, 'services/app/common/GetOrganizationUnits').then(rs => {
        // console.log('-----------')
        // console.log(rs)
        if (rs.success) {
          this.organizationUnitTree = rs.result
          // console.log(this.organizationUnitTree)
        }
      })
    },
    // 验证
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
           
          this.save()
          
        } else {
          console.log('error submit')
          return false
        }
      })
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
       this.$router.push({
          name: 'staff'
        })
    },
    // 树值
    getCheckedNodes() {
      // console.log(this.$refs.tree.getCheckedNodes())
      this.orgs = this.$refs.tree.getCheckedNodes()
      this.treename = [];
    },
    backs(){
    	console.log("back")
    	this.openTree = false
    	//this.formLabel.orgs=this.treeSelect
    	 this.$refs.tree.setCheckedKeys(this.treeSelect);
    },
    getCheckedKeys() {
    	if (this.value3!=='' && this.value3 !== null) {
    		this.formLabel.regionId = this.value3
    	}
      this.openTree = false
      this.getCheckedNodes()
      let half =this.$refs.tree.getHalfCheckedKeys();
      let check =this.$refs.tree.getCheckedKeys();
      check = check.concat(half) 
      this.treeSelect = check
      if(this.$refs.tree.getCheckedKeys().length == 0){
        this.formLabel.orgs= [];
      }else{
        this.formLabel.orgs=this.treeSelect
      }
      
    },
    linkage(){
    //	this.value2=''
      let params={
      };
      this.post(params, 'services/app/common/GetRegionsContainsPlateCode').then(rs => {
       this.aoptions=rs.result.items;
       	console.log("数据复制  省数据")
        console.log(this.aoptions)
      })
    },
    linkage2(val){ 
    	this.formLabel.value2=""
    	 this.value3=""
      this.formLabel.regionId = val
      let params={
        id:this.value1,
      }
        this.post(params,'services/app/common/GetRegionsContainsPlateCode').then(rs=>{
        	  this.boptions=rs.result.items;
        	  	console.log("数据复制  城市数据")
        	  	console.log(this.boptions)
        	  	
          	for(var i=0;i<this.boptions.length;i++){
	       			if(this.boptions[i].plateCode){
	       				this.boptions[i].conentname=this.boptions[i].value+'('+this.boptions[i].plateCode+')'
	       			}else{
	       				this.boptions[i].conentname=this.boptions[i].value
	       			}
             }
            
        })
      },
      linkage3(val){
      	console.log("qushuju------------------------")
      	console.log(val)
      	//val=val.key?val.key:val
      //this.value3=""
      this.formLabel.regionId = val
      console.log(val)
      if(this.id!="0"){
  				
      }else{
      	if(val.plateCode){
      		this.formLabel.value2=val.value+'('+val.plateCode+')'
      	}else{
      		this.formLabel.value2=val.value
      	}
      	 
      }
     
      val=val.key?val.key:val
      let params={
        id:val
      }
        this.post(params,'services/app/common/GetRegionsContainsPlateCode').then(rs=>{
          this.coptions=rs.result.items;
         		 console.log("数据复制  区数据")
        	  	console.log(this.coptions)
       	
//     		if (this.id != 0){
//	        	for(var i=0;i<this.coptions.length;i++){
//	       			if(this.coptions[i].key==val){
//	       				this.value2=this.coptions[i].value+'('+this.coptions[i].plateCode+')'
//	       			}
//	       		}
//	        }
       		
        })
      },
      linkage4(val){
        console.log(val)
        this.formLabel.regionId = val
      },
    // 保存
    save() {
      const that = this
      if (!this.from) {
        console.log('走创建')
        // 创建接口的参数
        const staffadd = Object.assign({},this.formLabel);
        if (typeof staffadd.regionId == 'object') {
        	staffadd.regionId = staffadd.regionId.key;
        }       
        console.log('wahah')
        console.log(staffadd);
        const paramsadd = {
          OrganizationUnitIds: this.treeSelect, // 组织树
          staff: staffadd
        }
        console.warn(paramsadd)
        console.log('787989')
        console.log(this.formLabel.regionId)
        // 判断走创建是不是选了组织权限
        that.post(paramsadd, 'services/app/staff/CreateStaff').then(rs => {
	        console.log(rs)
	        if (rs.success) {
	        	this.successNot();
	          console.log('成功-----------')
	         this.$router.push({
		          	name:"staff"
		          })
	          
	        }else{
	        	this.failNot(rs.error.message)
	        }
	      })
      } else {
        console.log('走编辑')
        // 编辑接口的参数
        const staffd = Object.assign({},this.formLabel);
        console.log('wahah')
        console.log(staffd);
        console.log('      --------------           ')
        const params = {
          OrganizationUnitIds: this.treeSelect, // 组织树
          staff: staffd
        }
        that.post(params, 'services/app/staff/UpdateStaff').then(rs => {
            console.log(rs)
            if (rs.success) {
              console.log('成功------------')
               this.successNot();
              this.$router.push({
                name: 'staff'
              })
             
            }else{
            	this.failNot(rs.error.message)
            }
          })
      }
    },
    //保存成功提示
    successNot(){
    	var txt = '';
    	if (this.id=='0') {
    		txt='工号新建成功'
    	} else{
    		txt='工号保存成功'
    	}
    	const h = this.$createElement;
      	this.$notify({
          title: '成功',
          message: txt,
          type: 'success',
          customClass:"el-notification-success"
       });
    },
    //保存失败提示
    failNot(message){
    	const h = this.$createElement;
      	this.$notify.error({
          title: '失败',
          message: message,
          duration: 0,
          customClass:"el-notification-error"
        });
    }

  }
}
</script>
<style lang="scss" scoped>

.floatLeft{float: left;}
  .staff{
    background-color:#fff;
  }
  .wd950{
    width:950px;
  }
  .left100{
    margin:15px 100px 0 120px;
  }
  .fix{
    min-height: 300px;
    overflow-y: auto;
    margin-left:100px;
    height:400px;
  }
  .el-row{
    padding:20px;
  }
  .center{
    text-align: center;
  }
  .offsetR{
    
  }
  .toBlock{
    display:block;
  }
  .org>.el-form-item__content{
    width:710px;
  }
  .ma20{
    margin-right: 20px;
  }
  .el-form-item.is-required .el-form-item__label:before{
    content: "*";
    color: #f56c6c;
    margin-right: 4px;
  }
  .setColor{
    color: #333;
    border-radius: 5px;
    background-color: #efefef;
    padding: 5px;
    border: 1px solid #d7d7d7;
    margin:0 20px 10px 0;
    display: inline-block;
    line-height:10px;
  }
  .setColor1{
    color:#0c7bde;
  }
  .hiddenInput{
    width:400px;
    height:0;
  }
  .wd230{
    width: 230px;
  }
  .staff{
    padding:25px;
  }
  .form-top{
      width: 100%;
      overflow: hidden;
      position: relative;
    .i{
      font-size:15px;
    }

    .form-title{
      font-size: 16px;
      color: #555;
    }
  }
  .form-top:after{
    display: block;
    height: 1px;
    width: 100%;
    position: absolute;
    left:103px;
    top:10px;
    background: #ddd;
    content: '';
  }
</style>
<style type="text/css">
	.regionId .el-form-item__content{width: 200px !important;}
</style>
